clear; clc; close all;

% 读取原始图像和加密图像（请确保路径正确）
I_orig = imread('Lena.tif');
if size(I_orig,3) == 3
    I_orig = rgb2gray(I_orig);
end
I_orig = double(I_orig);

I_enc = imread('Lena_encrypted.tif');
if size(I_enc,3) == 3
    I_enc = rgb2gray(I_enc);
end
I_enc = double(I_enc);

% 随机采样像素点数
N = 2000;

% 采样原图像邻近像素对
[xH_orig, yH_orig] = sample_adjacent_pixels(I_orig, N, 'horizontal');
[xV_orig, yV_orig] = sample_adjacent_pixels(I_orig, N, 'vertical');
[xD_orig, yD_orig] = sample_adjacent_pixels(I_orig, N, 'diagonal');

% 采样加密图像邻近像素对
[xH_enc, yH_enc] = sample_adjacent_pixels(I_enc, N, 'horizontal');
[xV_enc, yV_enc] = sample_adjacent_pixels(I_enc, N, 'vertical');
[xD_enc, yD_enc] = sample_adjacent_pixels(I_enc, N, 'diagonal');

% 绘图
figure;

subplot(2,3,1);
scatter(xH_orig, yH_orig, 1, '.');
title('Original - Horizontal');
xlabel('Pixel value');
ylabel('Adjacent pixel value');
axis square;

subplot(2,3,2);
scatter(xV_orig, yV_orig, 1, '.');
title('Original - Vertical');
xlabel('Pixel value');
ylabel('Adjacent pixel value');
axis square;

subplot(2,3,3);
scatter(xD_orig, yD_orig, 1, '.');
title('Original - Diagonal');
xlabel('Pixel value');
ylabel('Adjacent pixel value');
axis square;

subplot(2,3,4);
scatter(xH_enc, yH_enc, 1, '.');
title('Encrypted - Horizontal');
xlabel('Pixel value');
ylabel('Adjacent pixel value');
axis square;

subplot(2,3,5);
scatter(xV_enc, yV_enc, 1, '.');
title('Encrypted - Vertical');
xlabel('Pixel value');
ylabel('Adjacent pixel value');
axis square;

subplot(2,3,6);
scatter(xD_enc, yD_enc, 1, '.');
title('Encrypted - Diagonal');
xlabel('Pixel value');
ylabel('Adjacent pixel value');
axis square;


%% 子函数：采样邻近像素对
function [x_vals, y_vals] = sample_adjacent_pixels(I, N, direction)
    [rows, cols] = size(I);
    x_vals = zeros(N,1);
    y_vals = zeros(N,1);
    
    switch lower(direction)
        case 'horizontal'
            row_indices = randi([1, rows], N, 1);
            col_indices = randi([1, cols-1], N, 1);
            for k = 1:N
                x_vals(k) = I(row_indices(k), col_indices(k));
                y_vals(k) = I(row_indices(k), col_indices(k)+1);
            end
        case 'vertical'
            row_indices = randi([1, rows-1], N, 1);
            col_indices = randi([1, cols], N, 1);
            for k = 1:N
                x_vals(k) = I(row_indices(k), col_indices(k));
                y_vals(k) = I(row_indices(k)+1, col_indices(k));
            end
        case 'diagonal'
            row_indices = randi([1, rows-1], N, 1);
            col_indices = randi([1, cols-1], N, 1);
            for k = 1:N
                x_vals(k) = I(row_indices(k), col_indices(k));
                y_vals(k) = I(row_indices(k)+1, col_indices(k)+1);
            end
        otherwise
            error('Unknown direction');
    end
end
